<?php

namespace Biz\model\Album;

use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;

class AlbumWikiListModel extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    public const _TABLE_NAME = 'album_wiki_list';

    const STATUS_NORMAL = 1;
    // 状态为删除
    const STATUS_DELETE = 9;

    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return self::id();
    }

    public static function updateDataByWhere($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return true;
    }

    public static function selectByWhere($where, $field = '*')
    {
        return self::select($field, $where) ?? [];
    }

    public static function getCountMaps($map)
    {
        return self::select(['cnt' => Medoo::raw('count(album_id)'), 'album_id'], $map);
    }

    public static function getCountMapsByWiki($map)
    {
        return self::select(['cnt' => Medoo::raw('count(wiki_id)'), 'wiki_id'], $map);
    }

    public static function getByWhere($where , $field = '*')
    {
        return self::get($field , $where);
    }


    public static function getLatestAlbumId($wiki_id)
    {
        $data =  self::select(
            [
                "[>]" . AlbumListModel::_TABLE_NAME => ["album_id" => "album_id"],
            ],
            [
                self::_TABLE_NAME . ".album_id",
                self::_TABLE_NAME . ".wiki_id",
                self::_TABLE_NAME . ".id",
            ], [
                AlbumListModel::_TABLE_NAME.".status" => [1,2],
                AlbumListModel::_TABLE_NAME.".score[>=]" => 70,
                self::_TABLE_NAME.".wiki_id"=>$wiki_id,
                self::_TABLE_NAME.".status" => 1,
                'ORDER' => [self::_TABLE_NAME.".id" => 'DESC'],
            ]
        );

        $result = [];
        if($data && is_array($data)){
            foreach($data as &$val){
               if($result[$val['wiki_id']]) continue;
               $result[$val['wiki_id']] = $val['album_id'];
            }
        }
        return $result;
    }
}